﻿using System;
using System.Text;
using static TruckScale.Helpers.LogHelper;

namespace TruckScale.Helpers
{
  public static class ProtocolParseHelper
  {
    public static string ProtocolParse(byte[] byteBuf)
    {
      string protrcol = Global._weighConfig["Protocol"];
      string weighString;
      decimal weightNum;
      int decimalPoint;
      string ret = string.Empty;

      try
      {
        switch (protrcol)
        {
          case "耀华": //02 2B 30 30 30 30 30 30 32 31 3B 03

            int i = Array.IndexOf(byteBuf, (byte)0x02);

            if (i < 64 - 11 && byteBuf[i + 11] == 0x03)
            {
              weighString = Encoding.ASCII.GetString(byteBuf, i + 1, 7);

              weightNum = Convert.ToDecimal(weighString);

              decimalPoint = byteBuf[i + 8] - 0x30;

              if (Convert.ToBoolean(Global._weighConfig["WeighUnitConverter"]))
              {
                if (Global._weighConfig["WeighUnit"] == "t") //要把仪表的kg转换为t
                {
                  decimalPoint += 3;
                }
                else if (Global._weighConfig["WeighUnit"] == "kg")
                {
                  decimalPoint -= 3;
                }
              }

              while (decimalPoint-- > 0)
              {
                weightNum /= 10;
              }


              ret = weightNum.ToString();
            }
            break;
          default:
            break;
        }
      }
      catch (Exception e)
      {
        SetLog(e.Message, LogType.HardwareLogger, LogLevel.Error);
      }

      return ret;
    }
  }
}
